

package com.codegen.gbcodegen.controller;

import cn.hutool.core.io.IoUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.codegen.gbcodegen.entity.GenConfig;
import com.codegen.gbcodegen.service.SysGeneratorService;
import com.codegen.gbcodegen.util.R;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 代码生成器
 *
 */
@RestController
@AllArgsConstructor
@RequestMapping("/generator")
public class SysGeneratorController {

	private final SysGeneratorService sysGeneratorService;


	/**
	 * 生成代码
	 * 才疏学浅，目前想不出更好的办法来解决
	 * form 表单默认提交的格式application/x-www-form-urlencoded不可更改,所以不能用@RequestBody 实体类来接受
	 * @RequestBody接受参数会报错：Resolved exception caused by Handler execution: org.springframework.web.HttpMediaTypeNotSupportedException:
	 * Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported这样的错误。
	 */
	@SneakyThrows
	@RequestMapping(value = "/code", method = RequestMethod.POST )
	public void generatorCode(@RequestParam("packageName") String packageName,
			                  @RequestParam("tableName") String tableName,
							  @RequestParam("author") String author,
							  @RequestParam("moduleName") String moduleName,
							  @RequestParam("tablePrefix") String tablePrefix,
							  @RequestParam("comments") String comments, HttpServletResponse response) {
		GenConfig genConfig = new GenConfig();
		genConfig.setAuthor(author);
		genConfig.setComments(comments);
		genConfig.setModuleName(moduleName);
		genConfig.setPackageName(packageName);
		genConfig.setTableName(tableName);
		genConfig.setTablePrefix(tablePrefix) ;
		byte[] data = sysGeneratorService.generatorCode(genConfig);

		response.reset();
		response.setHeader(HttpHeaders.CONTENT_DISPOSITION, String.format("attachment; filename=%s.zip", genConfig.getTableName()));
		response.addHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length));
		response.setContentType("application/octet-stream; charset=UTF-8");

		IoUtil.write(response.getOutputStream(), Boolean.TRUE, data);
	}



}
